<template>
    <div class="financing-add-edit">
        <el-form ref="financing" :model="financing" :rules="rules" label-width="165px">
            <el-form-item label="车型图片（详情页）：" prop="detailFileList">
                <el-upload
                        action="#"
                        :class="{'local-hide': financing.detailFileList.length >= 1}"
                        :on-change="detailSelectFile"
                        :file-list="financing.detailFileList"
                        :multiple="false"
                        :limit="1"
                        list-type="picture-card"
                        :auto-upload="false">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                        >
                        <span class="el-upload-list__item-actions">
        <span
                class="el-upload-list__item-preview"
                @click="detailHandlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
                class="el-upload-list__item-delete"
                @click="detailHandleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                    </div>
                </el-upload>
                <el-dialog :append-to-body="true" :visible.sync="detailDialogVisible">
                    <img width="100%" :src="detailDialogImageUrl">
                </el-dialog>
                <span class="desc">图片大小750*470像素</span>
            </el-form-item>
            <el-form-item label="车型图片（列表页）：" prop="listFileList">
                <el-upload
                        action="#"
                        :class="{'local-hide': financing.listFileList.length >= 1}"
                        :on-change="listSelectFile"
                        :file-list="financing.listFileList"
                        :multiple="false"
                        :limit="1"
                        list-type="picture-card"
                        :auto-upload="false">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                        >
                        <span class="el-upload-list__item-actions">
        <span
                class="el-upload-list__item-preview"
                @click="listHandlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
                class="el-upload-list__item-delete"
                @click="listHandleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                    </div>
                </el-upload>
                <el-dialog :append-to-body="true" :visible.sync="listDialogVisible">
                    <img width="100%" :src="listDialogImageUrl">
                </el-dialog>
                <span class="desc">图片大小250*250像素</span>
            </el-form-item>
            <el-form-item label="名称（详情页）：" prop="detailName">
                <el-input v-model="financing.detailName"></el-input>
            </el-form-item>
            <el-form-item label="名称（列表页）：" prop="listName">
                <el-input v-model="financing.listName"></el-input>
            </el-form-item>
            <el-form-item label="标签：" prop="label">
                <el-input v-model="financing.label"></el-input>
                <span class="desc">标签之间请用英文（,）隔开</span>
            </el-form-item>
            <el-form-item class="flex-column" label="车型：" prop="brand_id">
                <el-select v-model="financing.brand_id" placeholder="请选择" @change="getSubBrandList">
                    <el-option v-for="(brand, index) in brandList" :key="brand.brand_id" :label="brand.brand_name" :value="brand.brand_id"></el-option>
                </el-select>
                <div class="b-group" v-for="(subBrand, index) in subBrandList" :key="subBrand.brand_id">
                    <div class="b-title">{{subBrand.brand_name}}</div>
                    <div class="b-list">
                        <el-radio v-for="(subSubBrand, index) in subBrand.child" v-model="financing.car_id" :key="subSubBrand.brand_id" :label="subSubBrand.brand_id">{{subSubBrand.brand_name}}</el-radio>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="外观描述：" prop="appearanceDesc">
                <el-input v-model="financing.appearanceDesc"></el-input>
            </el-form-item>
            <el-form-item label="厂商指导价（万）：" prop="storeGuidePrice">
                <el-input v-model="financing.storeGuidePrice"></el-input>
            </el-form-item>
            <el-form-item label="首付（万）：" prop="downPayment">
                <el-input v-model="financing.downPayment"></el-input>
            </el-form-item>
            <el-form-item label="月供（元）：" prop="monthPayment">
                <el-input v-model="financing.monthPayment"></el-input>
            </el-form-item>
            <el-form-item label="是否显示首付月供：">
                <el-radio-group style="margin-top: 8px;" v-model="financing.isShowDownMonth">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="0">关闭</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="期数（期）：" prop="periods">
                <el-input v-model="financing.periods"></el-input>
            </el-form-item>
            <el-form-item class="flex-column" label="店铺选择：" prop="storeList">
                <ul class="store-list" v-if="financing.storeList.length">
                    <li class="store-list-item" v-for="(store, index) in financing.storeList" :key="index">
                        <el-input @focus="showStoreBox(store)" v-model="store.store_name" readonly placeholder="店铺"></el-input>
                        <el-input v-model="store.contact_name" placeholder="联系人名字"></el-input>
                        <el-input v-model="store.contact_phone" placeholder="融资租赁电话"></el-input>
                        <el-button type="danger" @click="deleteStore(index)">删除</el-button>
                    </li>
                </ul>
                <el-button type="success" @click="addStore">添加店铺</el-button>
            </el-form-item>
            <el-form-item label="开始时间：" prop="startTime">
                <el-date-picker
                        v-model="financing.startTime"
                        type="date"
                        placeholder="开始时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：" prop="endTime">
                <el-date-picker
                        v-model="financing.endTime"
                        type="date"
                        placeholder="结束时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="金融方案列表：" prop="finFileList">
                <el-upload
                        action="#"
                        :class="{'local-hide': financing.finFileList.length >= 1}"
                        :on-change="finSelectFile"
                        :file-list="financing.finFileList"
                        :multiple="false"
                        :limit="1"
                        list-type="picture-card"
                        :auto-upload="false">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                        >
                        <span class="el-upload-list__item-actions">
        <span
                class="el-upload-list__item-preview"
                @click="finHandlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
                class="el-upload-list__item-delete"
                @click="finHandleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                    </div>
                </el-upload>
                <el-dialog :append-to-body="true" :visible.sync="finDialogVisible">
                    <img width="100%" :src="finDialogImageUrl">
                </el-dialog>
                <span class="desc"></span>
            </el-form-item>
            <el-form-item label="金融方案详情：">
                <tinymce :uploadData="uploadData" v-model="financing.finDetail"></tinymce>
            </el-form-item>
            <el-form-item label="车辆详情：">
                <tinymce :uploadData="uploadData" v-model="financing.carDetail"></tinymce>
            </el-form-item>
            <el-form-item class="btn-wrapper">
                <el-button @click="$emit('cancel')">取消</el-button>
                <el-button type="primary" @click="submitFinancing('financing')">确定</el-button>
            </el-form-item>
        </el-form>
        <store-list :showStoreBox="isShowStoreBox" @chooseStore="onChooseStore" @update:showStoreBox="hideStoreBox"></store-list>
    </div>
</template>

<script>
	import {dateFormatter} from "../../../../common/js/util";
	import StoreList from './../../../../components/home/store-list.vue';
	import Tinymce from './../../../../components/Tinymce/index';

	export default {
		data() {
			return {
				uploadData: {
					img_source: 'attach_finance_lease',
				},

				clickedStore: null,
				isShowStoreBox: false,

				detailDialogImageUrl: '',
				detailDialogVisible: false,

				listDialogImageUrl: '',
				listDialogVisible: false,

				finDialogImageUrl: '',
				finDialogVisible: false,

				financing: {
					detailFileList: [],
					listFileList: [],
					detailName: '',
					listName: '',
					label: '',
					brand_id: '',
					car_id: '',
					appearanceDesc: '',
					storeGuidePrice: '',
					downPayment: '',
					monthPayment: '',
					storeList: [],
					isShowDownMonth: 1,
					periods: '',
					startTime: '',
					endTime: '',
					finFileList: [],
					finDetail: '',
					carDetail: ''
				},

				rules: {
					detailFileList: [
						{ type: 'array', required: true, message: '请选择一张车型图片(详情页)', trigger: 'change' }
					],
					listFileList: [
						{ type: 'array', required: true, message: '请选择一张车型图片(列表页)', trigger: 'change' }
					],
					detailName: [
						{ required: true, message: '请输入名称(详情页)', trigger: 'blur' }
					],
					listName: [
						{ required: true, message: '请输入名称(列表页)', trigger: 'blur' }
					],
					label: [
						{ required: true, message: '请输入标签', trigger: 'blur' }
					],
					brand_id: [
						{ required: true, message: '请选择车型', trigger: 'change' }
                    ],
					appearanceDesc: [
						{ required: true, message: '请输入外观描述', trigger: 'blur' }
					],
					storeGuidePrice: [
						{ required: true, message: '请输入厂商指导价（万）', trigger: 'blur' }
					],
					downPayment: [
						{ required: true, message: '请输入首付（万）', trigger: 'blur' }
					],
					monthPayment: [
						{ required: true, message: '请输入月供（元）', trigger: 'blur' }
					],
					periods: [
						{ required: true, message: '请输入期数（期）', trigger: 'blur' }
					],
					storeList: [
						{ type: 'array', required: true, message: '请选择店铺', trigger: 'change' }
					],
					startTime: [
						{ type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
					],
					endTime: [
						{ type: 'date', required: true, message: '请选择结束时间', trigger: 'change' }
					],
					finFileList: [
						{ type: 'array', required: true, message: '请选择金融方案', trigger: 'change' }
					]
				},

				brandList: [],
                subBrandList: []
			}
		},
		props: {
			id: {
				type: Number,
				default: 0
			}
		},
		computed: {

		},
		methods: {
			hideStoreBox() {
				this.isShowStoreBox = false
            },
			onChooseStore(store) {
				this.clickedStore.store_id = store.storeId
				this.clickedStore.store_name = store.storeName
				this.clickedStore = null
            },
			showStoreBox(store) {
				this.isShowStoreBox = true;
				this.clickedStore = store;
            },
			deleteStore(index) {
				if (!this.financing.storeList[index].id) {
					this.financing.storeList.splice(index, 1);
                } else {
					this.$http.post('/admin/activity/index.php?act=finance_lease&op=delStore', {
						id: this.financing.storeList[index].id
					}).then(res => {
						if (res.code == 1) {
							this.financing.storeList.splice(index, 1);
                        } else {
							alert(res.msg);
                        }
                    })
                }
            },
			addStore() {
				this.financing.storeList.push({
                    store_id: 0,
                    store_name: '',
					contact_name: '',
					contact_phone: ''
                });
            },
			getFinancingDetail(id) {
				this.$http.post('/admin/activity/index.php?act=finance_lease&op=fl_edit', {
					fl_id: id
				}).then(res => {
					if (res.code == 1) {
						this.financing.detailName = res.data.finance_lease.fl_title_name
						this.financing.listName = res.data.finance_lease.fl_list_name
						this.financing.label = res.data.finance_lease.fl_tag

						this.financing.brand_id = res.data.finance_lease.fl_brand_id
						this.getSubBrandList(res.data.finance_lease.fl_brand_id)

						this.financing.car_id = res.data.finance_lease.fl_car_id
						this.financing.appearanceDesc = res.data.finance_lease.fl_facade_desc
						this.financing.storeGuidePrice = res.data.finance_lease.fl_original_price
						this.financing.downPayment = res.data.finance_lease.fl_down_payment
						this.financing.monthPayment = res.data.finance_lease.fl_monthly_payments
						this.financing.isShowDownMonth = res.data.finance_lease.fl_dm_show * 1
						this.financing.periods = res.data.finance_lease.fl_nper
						this.financing.finDetail = res.data.finance_lease.fl_standard_plan_desc
						this.financing.carDetail = res.data.finance_lease.fl_car_desc
						this.financing.startTime = new Date(res.data.finance_lease.fl_start_time * 1000)
						this.financing.endTime = new Date(res.data.finance_lease.fl_end_time * 1000)

                        if (res.data.store_list) {
	                        this.financing.storeList = res.data.store_list.map(item => {
		                        return {
		                        	id: item.id,
			                        store_id: item.store_id,
			                        store_name: item.store_name,
			                        contact_name: item.sa_name,
			                        contact_phone: item.fl_sms_mobile
		                        }
	                        })
                        }

						this.financing.detailFileList.push({
                            url: window.location.protocol + '//' + (document.domain == 'localhost' ? 'img.chejj.cn' : document.domain.replace('admin', 'img')) + '/upload/finance_lease/' + res.data.finance_lease.fl_car_img
                        })
						this.financing.listFileList.push({
							url: window.location.protocol + '//' + (document.domain == 'localhost' ? 'img.chejj.cn' : document.domain.replace('admin', 'img')) + '/upload/finance_lease/' + res.data.finance_lease.fl_list_car_img
						})
						this.financing.finFileList.push({
							url: window.location.protocol + '//' + (document.domain == 'localhost' ? 'img.chejj.cn' : document.domain.replace('admin', 'img')) + '/upload/finance_lease/' + res.data.finance_lease.fl_standard_plan_list
						})

					} else {
						alert(res.msg);
					}
				})
			},

			detailHandleRemove(file) {
				let index = this.financing.detailFileList.findIndex(item => item.url == file.url);
				this.financing.detailFileList.splice(index, 1);
			},
			detailHandlePictureCardPreview(file) {
				this.detailDialogImageUrl = file.url;
				this.detailDialogVisible = true;
			},
			detailSelectFile(file, fileList) {
				this.financing.detailFileList = fileList;
			},

			listHandleRemove(file) {
				let index = this.financing.listFileList.findIndex(item => item.url == file.url);
				this.financing.listFileList.splice(index, 1);
			},
			listHandlePictureCardPreview(file) {
				this.listDialogImageUrl = file.url;
				this.listDialogVisible = true;
			},
			listSelectFile(file, fileList) {
				this.financing.listFileList = fileList;
			},

			finHandleRemove(file) {
				let index = this.financing.finFileList.findIndex(item => item.url == file.url);
				this.financing.finFileList.splice(index, 1);
			},
			finHandlePictureCardPreview(file) {
				this.finDialogImageUrl = file.url;
				this.finDialogVisible = true;
			},
			finSelectFile(file, fileList) {
				this.financing.finFileList = fileList;
			},

			submitFinancing(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						let startTime = this.financing.startTime;
						let endTime = this.financing.endTime;
						if (endTime.getTime() <= startTime.getTime()) {
							this.$message({
								message: '开始时间必须在结束时间之前',
								type: 'error'
							});
							return
						}
						let data = new FormData();
						data.append('fl_title_name', this.financing.detailName);
						data.append('fl_list_name', this.financing.listName);
						data.append('fl_start_time', dateFormatter('YYYY-MM-DD', startTime));
						data.append('fl_end_time', dateFormatter('YYYY-MM-DD', endTime));
						data.append('fl_brand_id', this.financing.brand_id);
						data.append('fl_car_id', this.financing.car_id);
						data.append('fl_facade_desc', this.financing.appearanceDesc);
						if (isNaN(this.financing.storeGuidePrice)) {
							this.$message({
								message: '厂商指导价（万）必须是数字',
								type: 'error'
							});
							return
                        } else {
							data.append('fl_original_price', this.financing.storeGuidePrice);
                        }
						if (isNaN(this.financing.downPayment)) {
							this.$message({
								message: '首付（万）必须是数字',
								type: 'error'
							});
							return
                        } else {
							data.append('fl_down_payment', this.financing.downPayment);
                        }
						if (isNaN(this.financing.monthPayment)) {
							this.$message({
								message: '月供（元）必须是数字',
								type: 'error'
							});
							return
                        } else {
							data.append('fl_monthly_payments', this.financing.monthPayment);
                        }
						if (isNaN(this.financing.periods)) {
							this.$message({
								message: '期数（期）必须是数字',
								type: 'error'
							});
							return
                        } else {
							data.append('fl_nper', this.financing.periods);
                        }

						data.append('fl_standard_plan_desc', this.financing.finDetail);
						data.append('fl_car_desc', this.financing.carDetail);
						data.append('fl_tag', this.financing.label);
						data.append('fl_dm_show', this.financing.isShowDownMonth);

						let storeList = this.financing.storeList.filter(item => item.store_id && !item.id).map(item => { return {store_ids: item.store_id, store_names: item.store_name, store_tels: item.contact_phone, sa_name: item.contact_name} })
                        data.append('stores', JSON.stringify(storeList));

						if (this.financing.detailFileList.length) {
							let images = this.financing.detailFileList.map(function(item) {
								return item.raw ? item.raw : item.url;
							});
							for (let i=0; i<images.length; i++) {
								data.append('car_img', images[i]);
							}
						}

						if (this.financing.listFileList.length) {
							let images = this.financing.listFileList.map(function(item) {
								return item.raw ? item.raw : item.url;
							});
							for (let i=0; i<images.length; i++) {
								data.append('list_car_img', images[i]);
							}
						}

						if (this.financing.finFileList.length) {
							let images = this.financing.finFileList.map(function(item) {
								return item.raw ? item.raw : item.url;
							});
							for (let i=0; i<images.length; i++) {
								data.append('standard_plan_list', images[i]);
							}
						}

						let url = '/admin/activity/index.php?act=finance_lease&op=add'
                        if (this.id) {
                        	data.append('fl_id', this.id)
                            url = '/admin/activity/index.php?act=finance_lease&op=fl_update'
                        }

						this.$http.post(url, data).then(res => {
							if (res.code == 1) {
								let message = '';
								if (this.id) {
									message = '编辑成功'
								} else {
									message = '新增成功'
								}
								this.$message({
									message: message,
									type: 'success'
								})
								this.$emit('addEditSuccess')
								this.$emit('cancel')
							}
							else {
								alert(res.msg);
							}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
            getBrandList() {
	            this.$http.post('/admin/newCarGroupBuy/index.php?act=groupBuy&op=getChildBrand', {type: 'father', pid: 1}).then(res => {
	            	if (res.code == 1) {
                        this.brandList = res.data.map(item => {
                        	return {
		                        brand_id: item.brand_id,
		                        brand_name: item.brand_name
                            }
                        })
                    } else {
                        alert(res.msg)
                    }
                })
            },
			getSubBrandList(pid) {
				this.$http.post('/admin/newCarGroupBuy/index.php?act=groupBuy&op=getChildBrand', {pid}).then(res => {
					if (res.code == 1) {
						this.subBrandList = res.data.map(item => {
							return {
								brand_id: item.brand_id,
								brand_name: item.brand_name,
                                child: item.child
							}
						})
					} else {
						alert(res.msg)
					}
				})
            }
		},
		created() {
			if (this.id) {
				this.getFinancingDetail(this.id);
			}
			this.getBrandList();
		},
        components: {
	        StoreList,
	        Tinymce
        },
		name: "financing-add-edit"
	}
</script>

<style lang="scss" scoped>
    .financing-add-edit {
        padding: 0 20px;
    }
    /deep/ .el-form-item {
        padding-top: 22px;
        .el-form-item__content {
            display: flex;
            align-items: center;
            .el-input {
                width: 400px;
            }
            .desc {
                margin-left: 30px;
            }
        }
    }
    /deep/ .el-form-item.flex-column {
        .el-form-item__content {
            flex-direction: column;
            align-items: start;
            .b-group {
                margin-top: 15px;
                .b-title {
                    font-weight: 600;
                }
                .b-list {
                    padding-left: 15px;
                    max-width: 80%;
                }
            }
        }
        .store-list {
            margin-bottom: 15px;
            .store-list-item + .store-list-item {
                margin-top: 15px;
            }
            .store-list-item {
                .el-input {
                    width: 200px;
                    margin-right: 15px;
                }
            }
        }
    }
    /deep/ .local-hide .el-upload--picture-card {
        display: none;
    }
</style>
